import axios from 'axios';
import { ElMessage } from 'element-plus';

//创建axios对象
const service = axios.create({
    baseURL: '/path',
    timeout: 5 * 1000,
    headers: {
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
        Accept: 'application/json'
    }
});

//2.请求拦截器
service.interceptors.request.use(config => {
    //将请求的post的data转为json
    // config.data = JSON.stringify(config.data);
    //设置请求头
    if (config.url == '/news/update' || config.url == '/news/add' || config.url == '/users/update_user' || config.url == '/users/register' || config.url == '/category/updateCategory' || config.url == '/category/addCategory' || config.url == '/comment/add' || config.url == `/collection/addCollection` || config.url == `/approve/addApprove` || config.url == `/approve/deleteApprove` || config.url == `/collection/deleteCollection`) {
        config.headers = { 'Content-Type': 'application/json ; charset=utf-8' }
    }
    if (config.url == `/approve/deleteApprove` || config.url == `/collection/deleteCollection`) {
        config.data = config.params;
        config.params = null
    }
    return config;
}, error => {
    Promise.reject(error);
});

//3.响应拦截器
service.interceptors.response.use(response => {
    //判断code码
    const { data } = response
    if (data.code == 500) {
        ElMessage({
            message: data.msg,
            type: 'error',
        })
    }
    return response;
}
    , error => {
        return Promise.reject(error);
    });

export default service